package lynch.map 
{
	import lynch.Core.config.ration.Core.config.
	/**
	 * only open for WorldMap
	 * @author 小痛
	 */
	internal class TileFactory 
	{
		/**
		 * cache some tiles in pool
		 */
		private var tileVector:Vector.<Tile>;
		private var currentMapID:int;
		public var mosaicMap:MosaicMap;
		
		public function TileFactory() 
		{
			tileVector = new Vector.<Tile>(20);
		}
		
		public function updateInfo(currentMapID:int):void
		{
			this.currentMapID = currentMapID;
		}
		
		/**
		 * member variable always faster the static one
		 * @param	id
		 * @return
		 */
		public function getTile(id:int):Tile
		{
			var i:int, tile:Tile;
			
			for each (var item:Tile in tileVector) 
			{
				if (item)
				{
					//some times set to null is faster then splice
					tileVector[i] = null;
					
					tile = item;
					if (tile.id == id)
						return tile;
					
					tile.texture.dispose();
					tile.texture = mosaicMap.getMTexture(id);
					break;
				}
				++i;
			}
			tile ||= new Tile(mosaicMap.getMTexture(id));
			tile.updateInfo(id, currentMapID);
			tile.width = Core.config.tileWidth;
			tile.height = Core.config.tileHeight;
			return tile;
		}
		
		/**
		 * recover tiles in pool
		 * @param	tile
		 * @return	if the tile be cached suc
		 */
		public function recover(tile:Tile):Boolean
		{
			//only cache limited num of tiles
			var i:int = tileVector.indexOf(null);
			if (i != -1)
			{
				tileVector[i] = tile;
				return true;
			} else {
				tile.texture.dispose();
				return false;
			}
		}
	}

}